<?php


namespace App\Foundation\Utils;


use App\Exception\JWTExpireException;
use App\Exception\JWTException;
use Hyperf\Utils\Str;

class JWT


{
    //头部
    private static $header = array(
        'alg' => 'HS256', //生成signature的算法
        'typ' => 'JWT'    //类型
    );
    protected $config;

    public function __construct()
    {
        $this->config = config('jwt');
    }


    /**
     * 获取jwt token
     * @param array $claims jwt载荷
     * @return string
     */
    public function getToken(array $claims)
    {
        $payload = [
            'iss' => 'jwt_admin',  //该JWT的签发者
            'iat' => time(),  //签发时间
            'exp' => time() + $this->config['ttl'],  //过期时间
            'nbf' => time(),  //该时间之前不接收处理该Token
            'sub' => 'www.admin.com',  //面向的用户
            'jti' => md5(uniqid('JWT') . time())  //该Token唯一标识
        ];
        $payload = array_merge($payload, $claims);
        $header = [
            'alg' => $this->config['alg'], //生成signature的算法
            'typ' => 'JWT'//类型
        ];
        $base64header = self::base64UrlEncode(json_encode($header, JSON_UNESCAPED_UNICODE));
        $base64payload = self::base64UrlEncode(json_encode($payload, JSON_UNESCAPED_UNICODE));
        return $base64header . '.' . $base64payload . '.' . self::signature($base64header . '.' . $base64payload, $this->config['secret'], $header['alg']);

    }

    /**
     * 刷新token
     * @param string $token
     * @return String
     */
    public function refreshToken(string $token)
    {

        $claims = $this->getParserData($token);
        unset($claims['iat']);
        unset($claims['nbf']);
        unset($claims['exp']);
        unset($claims['jti']);
        return $this->getToken($claims);
    }

    public function getParserData($token): array
    {
        $tokens = explode('.', $token);
        list($base64header, $base64payload, $sign) = $tokens;
        return json_decode(self::base64UrlDecode($base64payload), JSON_OBJECT_AS_ARRAY);
    }

    /**
     * 处理token
     * @param string $token
     * @param string $prefix
     * @return bool|mixed|string
     */
    public static function handleToken(string $token, string $prefix = 'Bearer')
    {
        if (strlen($token) > 0) {
            $token = ucfirst($token);
            $arr = explode("{$prefix} ", $token);
            $token = $arr[1] ?? '';
            if (strlen($token) > 0) return $token;
        }
        return false;
    }


    /**
     * 验证token是否有效,默认验证exp,nbf,iat时间
     * @param string $Token 需要验证的token
     * @return bool|string
     */
    public function checkToken(string $Token)
    {
        $tokens = explode('.', $Token);
        if (count($tokens) != 3) {
            throw new JWTException('token invalid');
        }
        list($base64header, $base64payload, $sign) = $tokens;
        //获取jwt算法
        $base64decodeheader = json_decode(self::base64UrlDecode($base64header), JSON_OBJECT_AS_ARRAY);
        if (empty($base64decodeheader['alg'])) {
            throw new JWTException('token invalid');
        }
        //签名验证
        if (self::signature($base64header . '.' . $base64payload, $this->config['secret'], $base64decodeheader['alg']) !== $sign) {
            throw new JWTException('token invalid');
        }
        $payload = json_decode(self::base64UrlDecode($base64payload), JSON_OBJECT_AS_ARRAY);

        //签发时间大于当前服务器时间验证失败
        if (isset($payload['iat']) && $payload['iat'] > time()) {
            throw new JWTException('iat error');
        }
        //过期时间小宇当前服务器时间验证失败
        if (isset($payload['exp']) && $payload['exp'] < time()) {
            throw new JWTException('expired');
        }
        //该nbf时间之前不接收处理该Token
        if (isset($payload['nbf']) && $payload['nbf'] > time()) {
            throw new JWTException('nbf error');
        }
        return $payload;
    }


    /**
     * base64UrlEncode   https://jwt.io/  中base64UrlEncode编码实现
     * @param string $input 需要编码的字符串
     * @return string
     */
    private static function base64UrlEncode(string $input)
    {
        return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
    }

    /**
     * base64UrlEncode  https://jwt.io/  中base64UrlEncode解码实现
     * @param string $input 需要解码的字符串
     * @return bool|string
     */
    private static function base64UrlDecode(string $input)
    {
        $remainder = strlen($input) % 4;
        if ($remainder) {
            $addlen = 4 - $remainder;
            $input .= str_repeat('=', $addlen);
        }
        return base64_decode(strtr($input, '-_', '+/'));
    }

    /**
     * HMACSHA256签名   https://jwt.io/  中HMACSHA256签名实现
     * @param string $input 为base64UrlEncode(header).".".base64UrlEncode(payload)
     * @param string $key
     * @param string $alg 算法方式
     * @return mixed
     */
    private static function signature(string $input, string $key, string $alg = 'HS256')
    {
        $alg_config = array(
            'HS256' => 'sha256',
            'HS512' => 'sha512',
        );

        return self::base64UrlEncode(hash_hmac($alg_config[$alg], $input, $key, true));
    }

    public function getTTL()
    {
        return $this->config['ttl'];
    }
}

